package filter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.hibernate.Session;

import db.Album;
import db.DbUtils;
import db.Picture;


 public class FindServlet extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
	 private static final long serialVersionUID = 1L;
	 
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		String searchText = request.getParameter("find");
		String userName = (String)request.getSession().getAttribute("user");
		
		Session hbSession = DbUtils.startSession();
		Long userId = DbUtils.getUserIdByUserName(hbSession, userName);
		if (userId == null) {
		
		List<Picture> pictures=DbUtils.findPicture(hbSession, searchText);
		HttpSession session = request.getSession();
		session.setAttribute("findPictures", pictures);
		request.setAttribute("search", Boolean.TRUE);
		request.getRequestDispatcher("Home.jsp").forward(request, response);
		} else {
		long albumId = DbUtils.getALbumIdByName(hbSession, searchText, userId);
		
		List<Album> albums = new ArrayList<Album>();
		if (albumId != -1) {
			albums.add(DbUtils.getAlbumbyId(hbSession, albumId));
		}
		request.setAttribute("search", Boolean.TRUE);
		request.setAttribute("search_albums", albums);
		request.getRequestDispatcher("MyAlbum.jsp").forward(request, response);
		}
	}   	  	    
}